Moment.js 中文网 您所在的位置:网站首页 of what moment now is Moment.js 中文网

Moment.js 中文网

2024-06-02 15:59| 来源: 网络整理| 查看: 265

Moment.js 为原生 JavaScript 日期对象提供了一个封装器。在这样做时,Moment.js 扩展了功能并解决了对象中的几个缺陷。

¥Moment.js provides a wrapper for the native JavaScript date object. In doing this, Moment.js extends the functionality and also accounts for several deficiencies in the object.

使用原生日期进行解析尤其不可预测。例如,假设我在美国使用一台计算机,但我有一个 DD/MM/YYYY 格式的日期。

¥Parsing is notably unpredictable with native date. For instance, suppose I am using a computer in the United States, but I have a date in DD/MM/YYYY format.

var a = new Date('01/12/2016'); //December 1 2016 in DD/MM/YYYY format //"Tue Jan 12 2016 00:00:00 GMT-0600 (Central Standard Time)"

对于原生 Date 对象的这种行为没有好的解决方法。Moment 的解析器处理得很好:

¥There is no good work-around for this behavior with the native Date object. Moment's parser handles it just fine though:

moment('01/12/2016', 'DD/MM/YYYY', true).format() "2016-12-01T00:00:00-06:00"

此外,ECMA Script 5 规范对 ISO 8601 日期的偏移量做出了不寻常的断言:

¥In addition, the ECMA Script 5 Specification makes an unusual assertion about the offset of ISO 8601 dates:

缺少时区偏移量的值为 "Z"

¥The value of an absent time zone offset is "Z"

实际上,这意味着没有偏移量的 ISO 8601 日期将被视为 UTC 值,从而产生以下奇怪现象:

¥Effectively what this means is that ISO 8601 dates without an offset are to be treated as UTC values, creating the following oddity:

//US local format var a = new Date('1/1/2016'); //"Fri Jan 01 2016 00:00:00 GMT-0600 (Central Standard Time)" //ISO 8601 var a = new Date('2016-01-01'); //"Thu Dec 31 2015 18:00:00 GMT-0600 (Central Standard Time)"

ES2015 规范修复了这个错误,使其与 ISO8601 规范保持一致,后者指定本地时间不存在偏移量。这本身就很糟糕,因为它具有许多负面的向后兼容性影响。

¥The ES2015 spec fixes this mistake, bringing it in line with the ISO8601 specification, which specifies local time absent of offset. This is in it's own way bad as it has numerous negative back compatibility implications.

对于 Moment,日期始终被解释为本地时间,除非你另有说明。这不会随着 ES2015 的采用而改变。

¥With Moment, the date is always interpreted as local time, unless you specify otherwise. This is not something that will change with the adoption of ES2015.

moment('2016-01-01') //"2016-01-01T00:00:00-06:00"

算术是另一个缺少原生 Date 对象的字段。Date 对象实际上没有为此提供 API。相反,它依赖于溢出的日期值。假设你想将 2016 年 4 月 30 日增加 1 天。使用日期对象,你可以执行以下操作:

¥Arithmetic is another area where the native Date object is lacking. The Date object actually provides no API for this. Instead, it relies on overflowing date values. Suppose you wanted to add 1 day to April 30, 2016. With the date object you would do the following:

var a = new Date('4/30/2016'); a.setDate(a.getDate() + 1);

这可以解决问题,但有点不直观。Moment 提供了一个 API 来添加/减去:

¥This does the trick, but is somewhat unintuitive. Moment provides an API to add/subtract:

moment('4/30/2016', 'MM/DD/YYYY').add(1, 'day') //"2016-05-01T00:00:00-05:00"


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有